package com.unina.dropplayer.main;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.session.AccessTokenPair;
import com.example.dropplayer.R;
import com.unina.dropplayer.common.DropPlayerConstants;
import com.unina.dropplayer.common.ProgressListenerImpl;
import com.unina.dropplayer.download.DownloadActivity;
import com.unina.dropplayer.play.PlayActivity;
import com.unina.dropplayer.upload.UploadTask;
import com.unina.dropplayer.utilities.DropPlayerSessionBuilder;

public class MainActivity extends Activity {

	private DropboxAPI<AndroidAuthSession> mDBApi;
	private ImageButton loginButton, logoutButton, uploadButton,
			downloadButton, playButton;
	private Toast toast;
	private AccessTokenPair tokens;
	private boolean loggedIn;
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AndroidAuthSession session = DropPlayerSessionBuilder
				.buildSession(MainActivity.this);
		mDBApi = new DropboxAPI<AndroidAuthSession>(session);
		setContentView(R.layout.activity_main);

		initMainActivity();
		loggedIn = mDBApi.getSession().isLinked();

	}

	@Override
	protected void onResume() {
		super.onResume();

		if (mDBApi != null && null != mDBApi.getSession()
				&& mDBApi.getSession().authenticationSuccessful()) {

			try {

				toast = Toast.makeText(getApplicationContext(),
						"Login succeded", Toast.LENGTH_SHORT);
				// Required to complete auth, sets the access token on the
				// session
				mDBApi.getSession().finishAuthentication();
				toast.show();
				logoutButton.setVisibility(View.VISIBLE);
				uploadButton.setVisibility(View.VISIBLE);
				playButton.setVisibility(View.VISIBLE);
				downloadButton.setVisibility(View.VISIBLE);
				loginButton.setVisibility(View.GONE);
				tokens = mDBApi.getSession().getAccessTokenPair();
				storeKeys(tokens.key, tokens.secret);
				loggedIn = true;
			} catch (IllegalStateException e) {
				Log.i("DbAuthLog", "Error authenticating", e);
			}
		}
	}

	private void storeKeys(String key, String secret) {
		// Save the access key for later
		SharedPreferences prefs = getSharedPreferences(
				DropPlayerConstants.PREFS_NAME, 0);
		Editor edit = prefs.edit();
		edit.putString(DropPlayerConstants.PREF_APP_KEY_TOKEN, key);
		edit.putString(DropPlayerConstants.PREF_APP_SECRET_TOKEN, secret);
		edit.commit();
	}

	private void initMainActivity() {

		loginButton = (ImageButton) findViewById(R.id.buttonLogin);

		loginButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				mDBApi.getSession().startAuthentication(MainActivity.this);
			}
		});

		logoutButton = (ImageButton) findViewById(R.id.buttonLogout);
		logoutButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				logout();
			}
		});
		logoutButton.setVisibility(View.GONE);

		uploadButton = (ImageButton) findViewById(R.id.buttonUpload);
		uploadButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startUploadActivity();
			}
		});
		uploadButton.setVisibility(View.GONE);

		downloadButton = (ImageButton) findViewById(R.id.buttonDownload);
		downloadButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startDownloadActivity();
			}
		});
		downloadButton.setVisibility(View.GONE);

		playButton = (ImageButton) findViewById(R.id.buttonPlay);
		playButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startPlayActivity();

			}
		});
		playButton.setVisibility(View.GONE);

		if (null != mDBApi && null != mDBApi.getSession()
				&& mDBApi.getSession().isLinked()) {
			loginButton.setVisibility(View.GONE);
			downloadButton.setVisibility(View.VISIBLE);
			uploadButton.setVisibility(View.VISIBLE);
			playButton.setVisibility(View.VISIBLE);
			logoutButton.setVisibility(View.VISIBLE);
		}

	}

	private void startPlayActivity() {

		Intent intent = new Intent(this, PlayActivity.class);
		startActivity(intent);

	}

	private void startUploadActivity() {

		progressDialog = new ProgressDialog(MainActivity.this);
		progressDialog.setMessage(DropPlayerConstants.MESSAGE_UPLOADING);
		progressDialog.setIndeterminate(true);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setCancelable(false);
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("audio/*");
		startActivityForResult(intent, DropPlayerConstants.PICKFILE_RES_CODE);

	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		ProgressListener progressListener;
		UploadTask uploadTask;
		if (requestCode == DropPlayerConstants.PICKFILE_RES_CODE) {
			if (resultCode == RESULT_OK) {
				progressListener = new ProgressListenerImpl(progressDialog);
				uploadTask = new UploadTask(this, mDBApi, data.getData(),
						toast, progressListener, progressDialog);

				uploadTask.execute();

			}

		}
	}

	private void startDownloadActivity() {

		Intent intent = new Intent(this, DownloadActivity.class);
		startActivity(intent);

	}

	private void logout() {
		if (null != mDBApi && null != mDBApi.getSession()
				&& mDBApi.getSession().isLinked()) {
			mDBApi.getSession().unlink();
			DropPlayerSessionBuilder.clear(this);
			loginButton.setVisibility(View.VISIBLE);
			toast = Toast.makeText(getApplicationContext(), "Logout succeded",
					Toast.LENGTH_SHORT);
			toast.show();
			logoutButton.setVisibility(View.GONE);
			uploadButton.setVisibility(View.GONE);
			playButton.setVisibility(View.GONE);
			downloadButton.setVisibility(View.GONE);
			loggedIn = mDBApi.getSession().isLinked();
			;
		}
	}

}
